﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace SdmxMl.UC
{
    public class ComboAutoComplete : ComboBox
    {
        private bool _limitToList;
        public bool LimitToList
        {
            get { return _limitToList; }
            set { _limitToList = value; }
        }

        private bool _autoComplete;
        public bool AutoComplete
        {
            get { return _autoComplete; }
            set { _autoComplete = value; }
        }


        protected override void OnKeyPress(KeyPressEventArgs e)
        {

            if (_autoComplete)
                DoAutoComplete(this, e, _limitToList);
            base.OnKeyPress(e);

        }
       
		public void DoAutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e, bool blnLimitToList)
		{
			string strFindStr = "";

			if (e.KeyChar == ((char)Keys.Back))
			{
				if (cb.SelectionStart <= 1) 
				{
					cb.Text = "";
					return;
				}

				if (cb.SelectionLength == 0)
					strFindStr = cb.Text.Substring(0, cb.Text.Length - 1);
						else 
					strFindStr = cb.Text.Substring(0, cb.SelectionStart - 1);
					}
			else 
			{
				if (cb.SelectionLength == 0)
					strFindStr = cb.Text + e.KeyChar;
				else
					strFindStr = cb.Text.Substring(0, cb.SelectionStart) + e.KeyChar;
			}

			int intIdx = -1;

			// Search the string in the ComboBox list.
			
			intIdx = cb.FindString(strFindStr);
 
			if (intIdx != -1)
			{
				cb.SelectedText = "";
				cb.SelectedIndex = intIdx;
				cb.SelectionStart = strFindStr.Length;
				cb.SelectionLength = cb.Text.Length;
				e.Handled = true;
			}
			else
			{
				e.Handled = blnLimitToList;
			}

		}

    }
}
